import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import commonEventManager from '@ohos.commonEventManager';
import batteryInfo from '@ohos.batteryInfo';

export default class EntryAbility extends UIAbility {

  // 无法像官方示例一样限制类型为 commonEventManager.CommonEventSubscriber | null，不知道如何解决
  private subscriber = null;
  private storage: LocalStorage = new LocalStorage({
    'batterySOC': batteryInfo.batterySOC
  });

  onCreate(want, launchParam) {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');

    // 创建电池充电状态、电平和其他信息发生变化时的订阅者
    commonEventManager.createSubscriber({
      events: [commonEventManager.Support.COMMON_EVENT_BATTERY_CHANGED]
    })
      .then(data => {
        this.subscriber = data;

        if (this.subscriber !== null) {
          // 动态订阅公共事件回调
          commonEventManager.subscribe(this.subscriber, (err, data) => {
            if (err) {
              hilog.error(0x0000, 'testTag', '[BatteryChanged] Err=%{public}s', JSON.stringify(err) ?? '');
            } else {
              // 电池充电状态、电平和其他信息发生变化
              hilog.info(0x0000, 'testTag', '[BatteryChanged] Data=%{public}s', JSON.stringify(data) ?? '');
              // 逆天乱码，我宁愿重新从 batteryInfo 读取一遍，鬼知道这乱码华为什么时候修
              hilog.info(0x0000, 'testTag', '[BatteryChanged] BatteryLevel=%{public}d by parameters', data.parameters["뮠\r\u0001"] ?? '');

              const batterySOC: number = batteryInfo.batterySOC;
              hilog.info(0x0000, 'testTag', '[BatteryChanged] BatteryLevel=%{public}d by batteryInfo', batterySOC);
              if (this.storage.set('batterySOC', batterySOC) === false) {
                hilog.info(0x0000, 'testTag', '[BatteryChanged] Can not set localStorage value');
              }
            }
          })
        } else {
          hilog.error(0x0000, 'testTag', '[CommonEventManager] Need create subscriber');
        }
      })
      .catch(err => {
        hilog.error(0x0000, 'testTag', '[CommonEventManager] Failed to create subscriber. Code is %{public}d, message is %{public}s', err.code, err.message ?? '');
      })
  }

  onDestroy() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');

    // 销毁时取消动态订阅
    if (this.subscriber !== null) {
      commonEventManager.unsubscribe(this.subscriber, err => {
        if (err) {
          hilog.error(0x0000, 'testTag', '[CommonEventManager] UnsubscribeCallBack err=%{public}s', JSON.stringify(err) ?? '');
        } else {
          hilog.info(0x0000, 'testTag', '[CommonEventManager] Unsubscribe');
          this.subscriber = null;
        }
      })
    }
  }

  onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', this.storage, (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
